<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer v-bind="$attrs" :showFooter="false" :okAuth="'srm:scope:userOrderScope:edit'" @register="registerDrawer"
    @ok="handleSubmit" width="80%">
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      
      <template #qxfp>
        <!-- @click="handleEmployeeOfficeAdd" -->
        
        <div class="lg:flex">
          <div class="enter-y w-full !mr-4 lg:w-5/10" v-if="flagBm">
            <a-button @click="handleAddBm()" type="success" ghost class="mt-2 mb-2 mr-2 ml-2"  v-auth="'srm:scope:userOrderScope:edit'">
              <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('分配部门') }}
            </a-button>
            <Popconfirm :title="t('是否确认删除？')" @confirm="handleDeleteBm()">
              <a-button type="error" ghost class="mt-2 mb-2 " v-auth="'srm:scope:userOrderScope:edit'">
                <Icon icon="ant-design:delete-outlined" /> {{ t('批量删除') }}
              </a-button>
            </Popconfirm>
            <BasicTable @register="registerTableBm" />
          </div>
          <div class="enter-y w-full lg:w-5/10" v-if="flagGys">
            <a-button @click="handleAddGys()" type="success" ghost class="mt-2 mb-2 mr-2 ml-2" v-auth="'srm:scope:userOrderScope:edit'">
              <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('分配供应商') }}
            </a-button>
            <Popconfirm :title="t('是否确认删除？')" @confirm="handleDeleteGys()">
              <a-button type="error" ghost class="mt-2 mb-2" v-auth="'srm:scope:userOrderScope:edit'">
                <Icon icon="ant-design:delete-outlined" /> {{ t('批量删除') }}
              </a-button>
            </Popconfirm>
            <BasicTable @register="registerTableGys" />
          </div>
        </div>
      </template>
    </BasicForm>

    <ListSelect
        ref="listSelectRefBm"
        selectType="officeSelect"
        :checkbox="true"
        @select="handleSelectBm"
        :canSelectParent="false"
        v-show="false"
      />

      <ListSelect
        ref="listSelectRefGys"
        selectType="basVenSelect"
        :checkbox="true"
        @select="handleSelectGys"
        v-show="false"
      />

      <BasicModal v-bind="$attrs" @register="registerModal" title="分配部门" @ok="handleModal">
        <BasicForm @register="registerFormBm" />
      </BasicModal>

  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsSysEmpUserForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { EmpUser, checkEmpNo, empUserSave, empUserForm } from '/@/api/sys/empUser';
  import { checkLoginCode } from '/@/api/sys/user';
  import { officeTreeData } from '/@/api/sys/office';
  import { companyTreeData } from '/@/api/sys/company';
  import { basVenTreeData } from '/@/api/bas/ven/basVen';
  import { UserOrderScope, userOrderScopeSave, userOrderScopeForm } from '/@/api/srm/scope/userOrderScope';
  import { userOrderScopeDeptDelete, userOrderScopeDeptListData, userOrderScopeDeptSave  } from '/@/api/srm/scope/userOrderScopeDept';
  import { userOrderScopeVenDelete, userOrderScopeVenListData, userOrderScopeVenSave } from '/@/api/srm/scope/userOrderScopeVen';

  import { roleTreeData } from '/@/api/sys/role';
  import { BasicTable, useTable } from '/@/components/Table';
  import { ListSelect } from '/@/components/ListSelect';
  import { Popconfirm } from 'ant-design-vue';
  import { BasicModal, useModal } from '/@/components/Modal';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('sys.empUser');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref < EmpUser > ({} as EmpUser);
  const getTitle = computed(() => ({
    icon: meta.icon || 'ant-design:book-outlined',
    // value: record.value.isNewRecord ? t('新增用户') : t('编辑用户'),
    value: t('采购订单权限分配'),
  }));
  const ctrlPermi = ref < String > ('');
  const op = ref < String > ('');

  const listSelectRefBm = ref<any>(null);
  const listSelectRefGys = ref<any>(null);

  let flagBm = ref(false)
  let flagGys = ref(false)

  let scopeType = ref<any>('')

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('登录账号'),
      field: 'user.loginCode',
      component: 'Input',
      componentProps: {
        disabled: true
      },
      required: true,
    },
    {
      label: t('用户昵称'),
      field: 'user.userName',
      component: 'Input',
      componentProps: {
        disabled: true
      },
      required: true,
    },
     
    {
      label: t('权限分配'),
      field: 'roleInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },

    {
      label: t(''),
      field: 'scopeType',
      component: 'CheckboxGroup',
      componentProps: {
        dictType: 'srm_order_scope',
        onchange:(e,value)=>{
          console.log(e,value,'111');
          console.log( getFieldsValue(),'222');
          handleSubmit()
          let scopeType = getFieldsValue().scopeType
          flagBm.value = scopeType.includes('Dept')
          flagGys.value = scopeType.includes('Ven')
          if(flagBm.value){
            bmTable.reload()
          }
          if(flagGys.value){
            gysTable.reload()
          }
        }
      },
      colProps: { lg: 24, md: 24 },
    },
    // {
    //   label: '',
    //   field: 'detailInfo',
    //   component: 'Divider',
    //   colProps: { lg: 24, md: 24 },
    // },
    {
      label: t(''),
      field: 'qxfp',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'qxfp',
    },
  ];

  const searchFormBm: FormProps = {
    baseColProps: { lg: 12, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('部门名称'),
        field: 'office.officeName',
        component: 'Input',
      },
    ],
  };
  const searchFormGys: FormProps = {
    baseColProps: { lg: 12, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('供应商名称'),
        field: 'basVen.shortName',
        component: 'Input',
      },
    ],
  };

  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, updateSchema, validate }] = useForm({
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
    labelWidth: 120,
  });


  const [registerTableBm, bmTable] = useTable({
    columns: [
      {
        title: t('部门编码'),
        dataIndex: 'office.viewCode',
        width: 80,
        align: 'left',
      },
      {
        title: t('部门名称'),
        dataIndex: 'office.officeName',
        width: 130,
        align: 'left',
      },
     
    ],
    api: userOrderScopeDeptListData,
    beforeFetch: (params) => {
      params.userCode = record.value.userCode
      return params;
    },
    rowSelection: { type: 'checkbox' },
    // showTableSetting: true,
    useSearchForm: true,
    formConfig: searchFormBm,
    // pagination: false,
    // immediate: false,
    bordered: true,
    canResize: true,
  });

  const [registerTableGys, gysTable] = useTable({
    columns: [
      {
        title: t('供应商编码'),
        dataIndex: 'basVen.cuscode',
        width: 100,
        align: 'left',
      },
      {
        title: t('供应商名称'),
        dataIndex: 'basVen.shortName',
        width: 130,
        align: 'left',
      },
    ],
    api: userOrderScopeVenListData,
    beforeFetch: (params) => {
      params.userCode = record.value.userCode
      return params;
    },
    rowSelection: { type: 'checkbox' },
    formConfig: searchFormGys,
    // showTableSetting: true,
    useSearchForm: true,
    // pagination: false,
    // immediate: false,
    bordered: true,
    canResize: true,
  });


  const [registerFormBm, { resetFields:resetFieldsBm, validate:validateBm }] = useForm({
    labelWidth: 80,
    schemas: [
      {
        label: t('部门'),
        field: 'officeCode',
        fieldLabel: 'officeName',
        component: 'TreeSelect',
        componentProps: {
          api: officeTreeData,
          canSelectParent: true,
          allowClear: true,
          treeCheckable: true,
          // immediate: true,
        },
        required: true,
        colProps: { lg: 24, md: 24 },
        itemProps: { validateTrigger: 'blur' },
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerModal, { openModal, closeModal, setModalProps }] = useModal();

  

  async function setUserRoleTableData(res: Recordable) {
    const dataSource = await roleTreeData({
      userType: 'employee',
      ctrlPermi: ctrlPermi.value,
    });
    userRoleTable.setTableData(dataSource || []);
    userRoleTable.setSelectedRowKeys(res.roleList?.map((item) => item.id) || []);
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await userOrderScopeForm(data);
    record.value = (res.userOrderScope || {}) as UserOrderScope;
    record.value.__t = new Date().getTime();
    await setFieldsValue(record.value);
    let scopeType = record.value.scopeType || ''
    flagBm.value = scopeType.includes('Dept')
    flagGys.value = scopeType.includes('Ven')

    bmTable.reload()
    gysTable.reload()
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      // setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        userCode: record.value.userCode,
      };
      const res = await userOrderScopeSave(params, data);
      // showMessage(res.message);
      // setTimeout(closeDrawer);
      // emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      // setDrawerProps({ confirmLoading: false });
    }
  }

  

  async function handleAddBm() {
    // listSelectRefBm.value.openSelectModal();
    await openModal(true, {});
    resetFieldsBm();
  }

  function handleAddGys() {
    listSelectRefGys.value.openSelectModal();
  }

  

  

  async function handleModal() {
    try {
      const data = await validateBm();
      setModalProps({ confirmLoading: true });
       const params = {
        userCode: record.value.userCode,
        isNewRecord: true
      };
      const selIds = data.officeCode
      const res = await userOrderScopeDeptSave(params,{
        userCode: record.value.userCode,
        selIds
      });
      showMessage(res.message);
      bmTable.reload()
      setTimeout(closeModal);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
   }
  }
  async function handleSelectBm(values: Recordable[]) {
    if (values.length == 0) {
      showMessage(t('请选中要分配的部门'));
      return;
    }
    const params = {
      userCode: record.value.userCode,
      isNewRecord: true
    };
    const selIds = values.map(item=> item.officeCode).join(',')
    const res = await userOrderScopeDeptSave(params,{
      userCode: record.value.userCode,
      selIds
    });
    showMessage(res.message);
    bmTable.reload()
    listSelectRefBm.value.setSelectList([]);
  }

  async function handleSelectGys(values: Recordable[]) {
    if (values.length == 0) {
      showMessage(t('请选中要分配的供应商'));
      return;
    }
    const params = {
      userCode: record.value.userCode,
      isNewRecord: true
    };
    const selIds = values.map(item=> item.id).join(',')
    const res = await userOrderScopeVenSave(params,{
      userCode: record.value.userCode,
      selIds
    });
    showMessage(res.message);
    gysTable.reload()
    listSelectRefGys.value.setSelectList([]);
  }

  async function handleDeleteBm() {
    
    if (bmTable.getSelectRows().length) {
      var selIds = ref('');
      bmTable.getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      const res = await userOrderScopeDeptDelete({ selIds: selIds.value });
      showMessage(res.message);
      bmTable.reload()
    } else {
      showMessage('请先选择数据！！');
    }
  }

  async function handleDeleteGys() {
    if (gysTable.getSelectRows().length) {
      var selIds = ref('');
      gysTable.getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      const res = await userOrderScopeVenDelete({ selIds: selIds.value });
      showMessage(res.message);
      gysTable.reload()
    } else {
      showMessage('请先选择数据！！');
    }
  }



</script>